<?php
namespace app\controller;

use support\Request;
use support\Db;

class ShareController
{
    /**
     * 生成分享码
     */
    private function generateShareCode()
    {
        return md5(uniqid(mt_rand(), true));
    }

    /**
     * 验证用户是否有权限操作该账本
     */
    private function checkBookPermission($bookId, $userId)
    {
        return Db::table('account_book_users')
            ->where('book_id', $bookId)
            ->where('user_id', $userId)
            ->where('role', 1) // 必须是管理员
            ->where('status', 1)
            ->exists();
    }

    /**
     * 创建分享
     */
    public function create(Request $request)
    {
        try {
            $bookId = $request->post('book_id');
            
            if (empty($bookId)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 验证权限
            if (!$this->checkBookPermission($bookId, $request->uid)) {
                return json([
                    'code' => 403,
                    'msg' => '无权限操作'
                ]);
            }

            // 生成分享码
            $shareCode = $this->generateShareCode();
            
            // 设置24小时后过期
            $expireTime = date('Y-m-d H:i:s', strtotime('+24 hours'));

            // 创建分享记录
            $data = [
                'book_id' => $bookId,
                'user_id' => $request->uid,
                'share_code' => $shareCode,
                'expire_time' => $expireTime,
                'created_at' => date('Y-m-d H:i:s')
            ];

            Db::table('share_records')->insert($data);

            // 生成小程序路径
            $path = sprintf('pages/share/index?code=%s', $shareCode);

            return json([
                'code' => 0,
                'msg' => '创建成功',
                'data' => [
                    'share_code' => $shareCode,
                    'expire_time' => $expireTime,
                    'path' => $path
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 接受分享
     */
    public function accept(Request $request)
    {
        try {
            $shareCode = $request->post('share_code');
            
            if (empty($shareCode)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 查询分享记录
            $share = Db::table('share_records')
                ->where('share_code', $shareCode)
                ->where('status', 1)
                ->first();

            if (!$share) {
                return json([
                    'code' => 404,
                    'msg' => '分享链接不存在'
                ]);
            }

            // 验证是否过期
            if (strtotime($share->expire_time) < time()) {
                return json([
                    'code' => 400,
                    'msg' => '分享链接已过期'
                ]);
            }

            // 验证是否已经是账本成员
            $exists = Db::table('account_book_users')
                ->where('book_id', $share->book_id)
                ->where('user_id', $request->uid)
                ->where('status', 1)
                ->exists();

            if ($exists) {
                return json([
                    'code' => 400,
                    'msg' => '您已经是账本成员'
                ]);
            }

            // 添加为账本成员
            Db::beginTransaction();
            try {
                // 添加用户到账本
                Db::table('account_book_users')->insert([
                    'book_id' => $share->book_id,
                    'user_id' => $request->uid,
                    'role' => 0, // 普通成员
                    'created_at' => date('Y-m-d H:i:s')
                ]);

                // 使分享记录失效
                Db::table('share_records')
                    ->where('id', $share->id)
                    ->update([
                        'status' => 0,
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);

                Db::commit();

                return json([
                    'code' => 0,
                    'msg' => '加入成功'
                ]);
            } catch (\Exception $e) {
                Db::rollBack();
                throw $e;
            }
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取分享信息
     */
    public function info(Request $request)
    {
        try {
            $shareCode = $request->get('share_code');
            
            if (empty($shareCode)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 查询分享记录
            $share = Db::table('share_records as s')
                ->join('account_books as b', 's.book_id', '=', 'b.id')
                ->join('wa_users as u', 's.user_id', '=', 'u.id')
                ->where('s.share_code', $shareCode)
                ->where('s.status', 1)
                ->select([
                    'b.name as book_name',
                    'b.description as book_description',
                    'u.nickname as share_user_name',
                    'u.avatar as share_user_avatar',
                    's.expire_time'
                ])
                ->first();

            if (!$share) {
                return json([
                    'code' => 404,
                    'msg' => '分享链接不存在'
                ]);
            }

            // 验证是否过期
            $share->is_expired = strtotime($share->expire_time) < time();

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $share
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
} 